<?php
declare (strict_types = 1);

namespace app;

use app\admin\model\SystemConfig;
use EasyAdmin\console\CliEcho;
use EasyAdmin\tool\CommonTool;
use EasyAdmin\upload\driver\alioss\Oss;
use think\App;
use think\exception\ValidateException;
use think\Validate;

/**
 * 控制器基础类
 */
abstract class BaseController
{
    /**
     * Request实例
     * @var \think\Request
     */
    protected $request;

    /**
     * 应用实例
     * @var \think\App
     */
    protected $app;

    /**
     * 是否批量验证
     * @var bool
     */
    protected $batchValidate = false;

    /**
     * 控制器中间件
     * @var array
     */
    protected $middleware = [];

    /**
     * 构造方法
     * @access public
     * @param  App  $app  应用对象
     */
    public function __construct(App $app)
    {
        $this->app     = $app;
        $this->request = $this->app->request;

        // 控制器初始化
        $this->initialize();
    }

    // 初始化
    protected function initialize()
    {}

    /**
     * 验证数据
     * @access protected
     * @param  array        $data     数据
     * @param  string|array $validate 验证器名或者验证规则数组
     * @param  array        $message  提示信息
     * @param  bool         $batch    是否批量验证
     * @return array|string|true
     * @throws ValidateException
     */
    protected function validate(array $data, $validate, array $message = [], bool $batch = false)
    {
        if (is_array($validate)) {
            $v = new Validate();
            $v->rule($validate);
        } else {
            if (strpos($validate, '.')) {
                // 支持场景
                list($validate, $scene) = explode('.', $validate);
            }
            $class = false !== strpos($validate, '\\') ? $validate : $this->app->parseClass('validate', $validate);
            $v     = new $class();
            if (!empty($scene)) {
                $v->scene($scene);
            }
        }

        $v->message($message);

        // 是否批量验证
        if ($batch || $this->batchValidate) {
            $v->batch(true);
        }

        return $v->failException(true)->check($data);
    }

    const KEYS = [
        'RUSH_SCHEDULE' => "rush_schedule",
        'RUSH_GOODS' => "rush_goods_",
        'RUSH_GOODS_COUNTER' => "counter_rush_goods_",
        'USER_SMS' => "user_sms",
        'USER_GODTIME' => "user_godtime_",
        'USER_BLACKLIST' => "user_blacklist_",
        'USER_BLACKROOM' => "user_blackroom_",
        'USER_LIMIT' => "user_limit_",
        'USER_BELONG' => "user_blong",
        'USER_COMMON_LIMIT' => "user_common_limit",
        'USER_BADLIST' => "user_bad_",
        'SHELVES_GOODS' => "shelves_goods_",
        'SHELVES_GOODS_COUNTER' => "counter_shelves_goods",
        'BANNER_LIST' => "banner_list",
        'NOTICE_LIST' => "notice_list",
        'CATEGORY_LIST' => "category_list",
        'PROTOCOL_LIST' => "protocol_no_",
        'RATE_HANHDING' => "rate_handling_fee",
        'BUCKET_GOODS_LIST' => "bucket_goods_list_",
        'TOKEN' => "token_",
        'ADMIN_TOKEN' => "admin_token_",
        'GOODS_LAUNCH_TIME' => "goods_launch_time",
        'ALL_GOODS_LAUNCH_STATE' => 'all_goods_luanch_state',
        'GOODS_LAUNCH_GAIN' => "goods_luanch_gain",
        'LOG_SCHEDULE' => "LOG_S_",
        'LOG_SCHEDULE_RUSH_OK' => "LOG_S_OK_",
        'md5key' => "free",
    ];


    // 1更新用户信息
    // TODO 这里暂时排除 admin 的token, 以系统登录凭证为准
    // TODO 前端用户更新token使用这里更新redis
    public function updateUserInfo($uid, $admin = 0){
//        // 信息更新到redis
//        base.updateUserInfo = async (uid, admin) => {
//        let user_info = await mysql.query("SELECT * FROM user WHERE uid=?", [uid]);
//    if (user_info.length > 0) {
//        user_info = user_info[0];
//
//        delete user_info.pwd_md5;
//        delete user_info.admin_pwd;
//        user_info.roles = JSON.parse(user_info.roles);
//        let alist = await mysql.query("SELECT * FROM user_address WHERE uid=?", [uid]);
//        user_info.address_list = alist;
//
//        if (admin) {
//            let bucket_data = await base.checkUserRange(user_info);
//            user_info.isbucket = bucket_data.isbucket;
//            user_info.members = bucket_data.members;
//            await redis.Client1.setEx(`${KEYS.ADMIN_TOKEN}${uid}`, 86400 * 10, JSON.stringify(user_info));
//        }
//
//        await redis.Client1.setEx(`${KEYS.TOKEN}${uid}`, 86400 * 10, JSON.stringify(user_info));
//    }

    }

    // 2更新所有用户信息
    // TODO  仅在后台管理,新建 删除分仓时调用的
    public function updateAllUserInfo(){
//    base.updateAllUserInfo = async (uids) => {
//    if (uids.length > 0) {
//    for (let i = 0; i < uids.length; i++) {
//    let uid = uids[i];
//        // 信息更新到redis
//    let user_info = await mysql.query("SELECT * FROM user WHERE uid=?", [uid]);
//    if (user_info.length > 0) {
//    user_info = user_info[0];
//
//    delete user_info.pwd_md5;
//    delete user_info.admin_pwd;
//    user_info.roles = JSON.parse(user_info.roles);
//    let alist = await mysql.query("SELECT * FROM user_address WHERE uid=?", [uid]);
//    user_info.address_list = alist;
//
//    await redis.Client1.setEx(`${KEYS.TOKEN}${uid}`, 86400 * 10, JSON.stringify(user_info));
//                }
//            }
//        }
//
//    }
    }

    // 文件上传阿里云, 管理端调用或 前端调用
    // 抄 Apioss.php
    // TODO @zzz
    public function uploadoss(){

//        $dir = root_path() . 'public' . DIRECTORY_SEPARATOR . 'static';
//        $list = CommonTool::readDirAllFiles($dir);
//        $uploadConfig = sysconfig('upload');

        $uploadPrefix = config('app.oss_static_prefix', 'oss_static_prefix');
        $list = SystemConfig::select() ;
        $uploadConfig = collection($list)->toArray();

        $uploadConfig = array_column($uploadConfig,  'value', 'name') ;

//print_r($uploadConfig);die;
        try {
            $upload = Oss::instance($uploadConfig)
                ->save('$objectName', '$filePath');

        } catch (\Exception $e) {
            return ['code'=> 500, 'msg'=> '文件上传失败：' . '$filePath' . '。错误信息：' . $e->getMessage() ];
        }

        if ($upload['save'] == true) {
            return ['code'=> 200, 'msg'=> '', 'url'=> $upload['url'] ];
            //$msg = '文件上传成功：' . $filePath . '。上传地址：' . $upload['url'] ;
        } else {
            return ['code'=> 501, 'msg'=> $upload['msg'] ];
            // ('文件上传失败：' . $filePath . '。错误信息：' . $upload['msg']);
        }


    }

}
